import { defineStore } from 'pinia'
import { userLogin } from '@a/user'
import { ElMessage } from "element-plus";
import cookieApi from '@u/cookie'
import { removeUserInfo } from '@u/user'
const useUserStore = defineStore('user', {
  state: () => ({
    token:cookieApi.getCookie('token') || '',
    userInfo: cookieApi.getCookie('userInfo')?JSON.parse(cookieApi.getCookie('userInfo') as string) : {},
    role: cookieApi.getCookie('role') || ''
  }),
  actions: {
    // 用户登录
    userLogin(params: { userName: string; pwd: string }, routeParams: any) {
      userLogin(params).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('登录成功');
          this.token = res.data.token;
          this.userInfo = res.data.userInfo;
          this.role = res.data.role;
          // 跳转路由
          cookieApi.setCookie('token', this.token);
          cookieApi.setCookie('userInfo', JSON.stringify(this.userInfo));
          cookieApi.setCookie('role', this.role)
          
          if (routeParams.route.query.redirect) {   
            routeParams.router.replace(routeParams.route.query.redirect)
          } else {
            routeParams.router.replace('/dashBoard')
          }
         
        }
      })
    },
    // 退出登录
    userLogout(){
      removeUserInfo();
    }
  }
})

export default useUserStore
